import { videoCall, getImUser } from '@/network/apis';
import { toast } from '@/utils';

export const setEnable1v1Chat = () => {
	wx.setEnable1v1Chat({
		enable: true,
		success: function (res) {},
		fail: function (err) {
			console.log(err, 'err');
			toast.error('通话未授权');
		}
	});
};

export const getCallerAndListener = (workOrderId) => {
	return new Promise(async (resolve, reject) => {
		const { data } = await getImUser(workOrderId);

			const { sender, receiver } = data;

			const caller = {
				nickname: sender.username,
				openid: sender.openId
			};

			const listener = {
				nickname: receiver.username,
				openid: receiver.openId
			};

			return resolve({ caller, listener })
	})
}

export const join1v1Chat = async (workOrderId) => {
	let timer = null;

	const clearTimer = () => {
		if (timer) {
			timer = null;
			clearTimeout(timer);
		}
	};

	wx.onVoIPVideoMembersChanged(res => {
		clearTimer();
		console.log('---onVoIPVideoMembersChanged 实时语音通话成员视频状态变化事件', res);
	});

	wx.onVoIPChatStateChanged(res => {
		clearTimer();
		console.log('---onVoIPChatStateChanged 房间状态', res);
	});

	wx.onVoIPChatInterrupted(res => {
		clearTimer();
		console.log('onVoIPChatInterrupted 被动挂断', res);
	});

	wx.onVoIPChatMembersChanged(res => {
		clearTimer();
		console.log('onVoIPChatMembersChanged 对方挂断', res);
	});

	wx.offVoIPVideoMembersChanged(res => {
		clearTimer();
		console.log('offVoIPVideoMembersChanged', res);
	});

	return new Promise(async (resolve, reject) => {
		const { caller, listener } = await getCallerAndListener(workOrderId);
		console.log("🚀 ~ returnnewPromise ~ caller, listener:", caller, listener)

		if (!caller.openid || !listener.openid) {
			toast.error('接单后才能拨打电话');
			return;
		}

		wx.join1v1Chat({
			caller: caller,
			listener: listener,
			roomType: 'video', // video
			success: res => {
				timer = setTimeout(async () => {
					await videoCall(workOrderId);
				}, 5000);

				console.log('开启聊天成功', res);
				return resolve()
			},
			fail: res => {
				console.log('开启聊天失败', res);
				return reject();
			},
			complete: res => {
				console.log('开启聊天结束', res);
			}
		});
	});
};
